<template>
	<view class="select_user">
		<view style="padding: 10rpx;">
			<uni-segmented-control :current="current" :values="subsectionList" :style-type="'button'"
				:active-color="'#2979ff'" @clickItem="sectionChange" />
			<view style="margin-top: 10rpx;">
				<uni-search-bar placeholder="请输入用户名称" :show-action="false" v-model:modelValue="keyword"
					@confirm="handleSearch"></uni-search-bar>
			</view>
		</view>
		<view class="select_user_con">
			<!-- <scroll-view scroll-y="true" style="height: 100%;"> -->
				<view class="select_user_con_box" v-if="current == 0">
					<view v-for="(item, index) in newRecentSelectedList" :key="item.uuid">
						<l-checkbox @update:modalValue="item.checked = $event" :modalValue="item.checked"
							:name="item.key" @change="(val) => handleClickItem(val, item, index)"
							:textAfter="`${item.title}${item.dept ? item.dept : ''}`"></l-checkbox>
					</view>
				</view>
				<view class="select_user_con_box flex_col" v-if="current == 1">
					<view v-if="!keyword">
						<view style="display: flex;flex-wrap: wrap;color:rgba(0,0,0,.7)" @click="handleTkiTreeDepart"
							v-if="departmentSelected && departmentSelected.length">
							<view class="" v-for="(item, index) in departmentSelected" :key="item.uuid">
								{{ item.label }} <uni-icons type="right"></uni-icons>
							</view>
						</view>
						<view style="color:rgba(0,0,0,.7)" @click="handleTkiTreeDepart" v-else>
							选择部门<uni-icons type="right"></uni-icons>
						</view>
					</view>
					<view class="flex_1">
						<view v-for="(item, index) in newDepartUser" :key="item.uuid">
							<l-checkbox @update:modalValue="item.checked = $event" :modalValue="item.checked"
								@change="(val) => handleClickItem(val, item, index)"
								:textAfter="`${item.title}${item.dept ? item.dept : ''}`"></l-checkbox>
						</view>
					</view>
				</view>
				<view class="select_user_con_box" v-if="current == 2">
					<view v-if="!keyword">
						<view style="display: flex;flex-wrap: wrap;color:rgba(0,0,0,.7)" @click="handleTkiTreeRole"
							v-if="roleListSelected && roleListSelected.length">
							<view class="" v-for="(item, index) in roleListSelected" :key="item.uuid">
								{{ item.label }} <uni-icons type="right"></uni-icons>
							</view>
						</view>
						<view style="color:rgba(0,0,0,.7)" @click="handleTkiTreeRole" v-else>
							选择角色<uni-icons type="right"></uni-icons>
						</view>
					</view>
					<view class="flex_1">
						<view v-for="(item, index) in newRoleUser" :key="item.uuid">
							<l-checkbox @update:modalValue="item.checked = $event" :modalValue="item.checked"
								@change="(val) => handleClickItem(val, item, index)"
								:textAfter="`${item.title}${item.dept ? item.dept : ''}`"></l-checkbox>
						</view>
					</view>
				</view>
				<view class="select_user_con_box" v-if="current == 3">
					<view v-if="!keyword">
						<view style="display: flex;flex-wrap: wrap;color:rgba(0,0,0,.7)" @click="handleTkiTreeGroup"
							v-if="groupListSelected && groupListSelected.length">
							<view class="" v-for="(item, index) in groupListSelected" :key="item.uuid">
								{{ item.label }} <uni-icons type="right"></uni-icons>
							</view>
						</view>
						<view style="color:rgba(0,0,0,.7)" @click="handleTkiTreeGroup" v-else>
							选择用户组<uni-icons type="right"></uni-icons>
						</view>
					</view>
					<view class="flex_1">
						<view v-for="(item, index) in newGroupUser" :key="item.uuid">
							<l-checkbox @update:modalValue="item.checked = $event" :modalValue="item.checked"
								@change="(val) => handleClickItem(val, item, index)"
								:textAfter="`${item.title}${item.dept ? item.dept : ''}`"></l-checkbox>
						</view>
					</view>
				</view>

			<!-- </scroll-view> -->
		</view>
		<view
			style="display: flex; align-items: center; border-top: 1px solid #ccc;border-bottom: 1px solid #ccc;padding: 10rpx;">
			<view style="width: 100rpx;">
				已选：
			</view>
			<view style="width:calc(100% - 100rpx);">
				<scroll-view scroll-y="true" style="max-height: 150rpx;">
					<view style="display: flex;gap: 10rpx;flex-wrap: wrap;">
						<view v-for="(item, index) in selectUserList" :key="item.uuid"
							style="display: flex;gap:10rpx;border: 1px solid #a0cfff;padding: 0 14rpx;border-radius: 6rpx;cursor: pointer;align-items: center;background-color: #ecf5ff;color: #2979ff;font-size: 28rpx;">
							{{ item.title }}
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
		<TkiTree idKey="key" :range="departmentList" ref="tkiTreeDepartRef" @confirm="handleTkiTreeDepartConfirm" />
		<TkiTree idKey="key" :range="roleList" ref="roleListRef" @confirm="handleTkiTreeRoleListConfirm" />
		<TkiTree idKey="key" :range="groupList" ref="groupListRef" @confirm="handleTkiTreeGroupListConfirm" />
	</view>
</template>

<script>
	import TkiTree from '@/components/tki-tree/tki-tree.vue'
	import {
		mapState
	} from "vuex";
	import {
		postFormAction,
	} from "@/utils/request.js";
	import {
		randomUUID
	} from '@/utils/util.js'
	export default {
		components: {
			TkiTree
		},
		data() {
			return {
				url: {
					getRoleUsers: '/user/getRoleUsers', //角色查人员
					getDeptUsers: '/user/getDeptUsers', //部门查人员
					getGroupUsers: '/user/getGroupUsers', //用户组查人员
					listLikeRealName: "/user/listLikeRealName", //查询人员
				},
				subsectionList: ['最近', '部门', '角色', '用户组'],
				current: 0,
				recentSelectedList: [], //最近
				selectUserList: [], //已选
				departmentList: [], //部门
				departmentSelected: [], //部门已选
				departUser: [], //部门用户
				roleList: [], //角色
				roleListSelected: [], //角色已选
				roleUser: [], //角色用户
				groupList: [], //用户组
				groupUser: [], //用户组用户
				groupListSelected: [], //用户组已选
				keyword: '', //查询用户
				searchUser: [], //查询到的用户
			}
		},
		mounted() {
			this.fetch()
		},
		computed: {
			...mapState(["loginInfo"]),
			newRecentSelectedList() {
				return this.keyword ? this.searchUser : this.recentSelectedList
			},
			newDepartUser() {
				return this.keyword ? this.searchUser : this.departUser
			},
			newRoleUser() {
				return this.keyword ? this.searchUser : this.roleUser
			},
			newGroupUser() {
				return this.keyword ? this.searchUser : this.groupUser
			},
		},
		methods: {
			fetch() {
				//初始化各个tab数据
				postFormAction('/userMultiSel').then((res) => {
					console.log("userMultiSel", res)
					const {
						data
					} = res
					this.recentSelectedList = data.recentSelectedList || [];
					this.recentSelectedList = this.recentSelectedList.filter(item => item.name != this.loginInfo
						.userName)
					this.recentSelectedList.forEach((item) => {
						item.key = item.name;
						item.label = item.realName;
						item.title = item.realName;
						item.uuid = randomUUID()
						item.checked = false
					});
					this.roleList = data.roleList;
					this.roleList.forEach((item) => {
						item.key = item.code;
						item.label = item.description;
						item.title = item.description;
						item.uuid = randomUUID()
					});
					this.groupList = data.groupList;
					this.groupList.forEach((item) => {
						item.key = item.code;
						item.label = item.description;
						item.title = item.description;
						item.uuid = randomUUID()
					});
					this.departmentList = this.getChildren(data.departmentList, 'name', 'code') || [];

				});
			},
			getChildren(data, name, key) {
				if (!data) return
				data.forEach(node => {
					node.key = node[key]
					node.title = node[name]
					node.value = node[key]
					node.label = node[name]
					node.uuid = randomUUID()
					if (node.children && node.children.length > 0) {
						this.getChildren(node.children, name, key)
					}
				});
				return data
			},
			clear() {
				this.keyword = ''
				this.searchUser = []
				this.current = 0
			},
			sectionChange(e) {
				this.current = e.currentIndex;
				this.keyword = ''
				this.searchUser = []
			},
			//点击用户人员
			handleClickUserRecent(e, item, index) {
				const record = this.recentSelectedList[index]
				record.checked = e.value
				this.recentSelectedList[index] = {
					...record
				}
				this.handleClickUser(record)
			},
			//点击部门人员
			handleClickUserDepart(e, item, index) {
				const record = this.departUser[index]
				record.checked = e.value
				this.departUser[index] = {
					...record
				}
				this.handleClickUser(record)
			},
			//点击角色人员
			handleClickUserRole(e, item, index) {
				const record = this.roleUser[index]
				record.checked = e.value
				this.roleUser[index] = {
					...record
				}
				this.handleClickUser(record)
			},
			//点击用户组人员
			handleClickUserGroup(e, item, index) {
				const record = this.groupUser[index]
				record.checked = e.value
				this.groupUser[index] = {
					...record
				}
				this.handleClickUser(record)
			},
			//点击选中
			handleClickItem(e, item, index) {
				if (this.keyword) {
					const record = this.searchUser[index]
					record.checked = e.value
					this.searchUser[index] = {
						...record
					}
					this.handleClickUser(record)
				} else {
					if (this.current == 0) {
						this.handleClickUserRecent(e, item, index)
					} else if (this.current == 1) {
						this.handleClickUserDepart(e, item, index)
					} else if (this.current == 2) {
						this.handleClickUserRole(e, item, index)
					} else if (this.current == 3) {
						this.handleClickUserGroup(e, item, index)
					}
				}
			},
			//更新选中人员
			handleClickUser(record) {
				const keys = this.selectUserList.map(item => item.key)
				if (record.checked) {
					if (!keys.includes(record.key)) {
						this.selectUserList.push(record)
					}
				} else {
					this.selectUserList = this.selectUserList.filter(item => item.key != record.key)
				}
				// this.selectUserList.forEach(item => {
				// 	item.uuid = randomUUID()
				// })
				this.$forceUpdate()
			},
			//选择部门
			handleTkiTreeDepart() {
				this.$refs.tkiTreeDepartRef._show()
			},
			//部门回调
			handleTkiTreeDepartConfirm(e) {
				if (e && e.length) {
					this.departmentSelected = []
					e.forEach(el => {
						if (el.parents && el.parents.length) {
							el.parents.forEach(item => {
								this.departmentSelected.push(item)
							})

							this.departmentSelected.push({
								...el,
								parents: []
							})
						} else {
							this.departmentSelected = [el]
						}
					})
				}
				if (this.departmentSelected && this.departmentSelected.length) {
					this.getDeptUsersList(this.departmentSelected[this.departmentSelected.length - 1].key)
				}

			},
			getDeptUsersList(deptCode) {
				//通过部门获取用户
				try {
					uni.showLoading({
						title: '查询中',
						mask: true
					})

					let params = {
						op: 'getDeptUsers',
						deptCode: deptCode,
						isIncludeChildren: false,
						limitDepts: '',
					};
					//初始化各个tab数据
					postFormAction(this.url.getDeptUsers, params).then((res) => {
						const {
							data
						} = res
						const list = data.list || [];
						this.departUser = list.filter(item => item.name != this.loginInfo.userName)
						this.departUser.forEach((item) => {
							item.key = item.name;
							item.title = item.realName;
							item.checked = false
							item.uuid = randomUUID()
						});
					});
				} catch (e) {
					console.error(e)
				} finally {
					uni.hideLoading()
				}
			},

			//选择角色
			handleTkiTreeRole() {
				this.$refs.roleListRef._show()
			},
			//角色回调
			handleTkiTreeRoleListConfirm(e) {
				if (e && e.length) {
					this.roleListSelected = []
					e.forEach(el => {
						if (el.parents && el.parents.length) {
							el.parents.forEach(item => {
								this.roleListSelected.push(item)
							})

							this.roleListSelected.push({
								...el,
								parents: []
							})
						} else {
							this.roleListSelected = [el]
						}
					})
				}
				if (this.roleListSelected && this.roleListSelected.length) {
					this.getRoleUsersList(this.roleListSelected[0].key)
				}
			},
			getRoleUsersList(code) {
				//通过角色获取用户
				try {
					uni.showLoading({
						title: '查询中',
						mask: true
					})
					let params = {
						roleCode: code,
					};
					postFormAction(this.url.getRoleUsers, params).then((res) => {
						const {
							data
						} = res
						const list = data || [];
						this.roleUser = list.filter(item => item.name != this.loginInfo.userName)
						this.roleUser.forEach((item) => {
							item.key = item.name;
							item.title = item.realName;
							item.checked = false
							item.uuid = randomUUID()
						});
					});
				} catch (e) {
					console.error(e)
				} finally {
					uni.hideLoading()
				}
			},

			//选择用户组
			handleTkiTreeGroup() {
				this.$refs.groupListRef._show()
			},
			//用户组回调
			handleTkiTreeGroupListConfirm(e) {
				if (e && e.length) {
					this.groupListSelected = []
					e.forEach(el => {
						if (el.parents && el.parents.length) {
							el.parents.forEach(item => {
								this.groupListSelected.push(item)
							})

							this.groupListSelected.push({
								...el,
								parents: []
							})
						} else {
							this.groupListSelected = [el]
						}
					})
				}
				if (this.groupListSelected && this.groupListSelected.length) {
					this.getGroupUsersList(this.groupListSelected[0].key)
				}
			},
			getGroupUsersList(code) {
				//通过用户组获取用户

				try {
					uni.showLoading({
						title: '查询中',
						mask: true
					})
					let params = {
						groupCode: code,
					};
					postFormAction(this.url.getGroupUsers, params).then((res) => {
						const {
							data
						} = res
						const list = data || [];
						this.groupUser = list.filter(item => item.name != this.loginInfo.userName)
						this.groupUser.forEach((item) => {
							item.key = item.name;
							item.title = item.realName;
							item.checked = false
							item.uuid = randomUUID()
						});
					});
				} catch (e) {
					console.error(e)
				} finally {
					uni.hideLoading()
				}
			},

			//查询用户
			async handleSearch(e) {
				try {
					uni.showLoading({
						title: '查询中',
						mask: true
					})
					const res = await postFormAction(this.url.listLikeRealName, {
						realName: this.keyword
					})
					const {
						data
					} = res
					if (data && data.length > 0) {
						const keys = this.selectUserList.map(item => item.key)
						let list = data.filter(item => item.name != this.loginInfo.userName)
						this.searchUser = list.map(item => {
							return {
								...item,
								key: item.name,
								title: item.realName,
								checked: keys.includes(item.name),
								uuid: randomUUID()
							}
						})
					}
				} catch (e) {

				} finally {
					uni.hideLoading()
				}
			},

		}
	}
</script>

<style lang="scss" scoped>
	.select_user {
		/* #ifdef APP || MP-WEIXIN */
		height: 100%;
		/* #endif */
		/* #ifdef H5 */
		height: 100%;
		/* #endif */
		display: flex;
		flex-direction: column;

		.select_user_con {
			flex: 1;
			overflow-y: auto;

			.select_user_con_box {
				padding: 20rpx;
				display: flex;
				flex-direction: column;
				gap: 20rpx;
			}
		}
	}

	.flex_col {
		height: 100%;
		display: flex;
		flex-direction: column;
	}

	.flex_1 {
		flex: 1;
		overflow-y: auto;
	}

	.u-checkbox {
		width: 100%;
	}
</style>